<%@ page pageEncoding="UTF-8"%>
<%@ include file="/common/token.jsp"%>
<%@ include file="/common/user.jsp"%>
<%@ include file="/common/visit.jsp"%>
<%@ include file = "/common/operatehistory.jsp"%>
<%
	// 给患者创建随访计划
	Integer uid = token.getUid();
	User doctor = userByUid(uid);
	if (!USER_EMPLOYEE.equals(doctor.getType())) {
		msg = new Message(30041, "您没有权限创建随访计划");
		Tools.encryptPrint(out, msg);
		return;
	}
	Integer id = input.getInt("template_id", -1);
	List<String> patientUids = stringToList(input.getDesc("patient_uid"));
	String patients = "-1";
	for (String str:patientUids) {
		patients = patients + "," + str;
	}
	Integer push = input.getInt("push", 0);
	Integer startPointId = input.getInt("start_point_id", -1);
	String startTime = input.getDesc("start_time", "").trim() + SURVEY_PUSH_TIME;
	Date start = null;
	try {
		start = new SimpleDateFormat(DateUtil.DATETIME_FORMAT).parse(startTime);
	} catch (Exception e) {
		msg = new Message(30041, "基准时间格式错误");
		Tools.encryptPrint(out, msg);
		return;
	}
	List<Map> templates = QBuilder.db("basedb").select().from("visit_template").where(new Where("id =", id).and("status = ", STATUS_ENABLE).and("uid=", uid)).query().getResultObj();
	if (isEmpty(templates)) {
		msg = new Message(30041, "随访方案不存在");
		Tools.encryptPrint(out, msg);
		return;
	}
	Map template = templates.get(0);
	Map startPointMap = new HashMap();
	List<Map> points = QBuilder.db("basedb").select().from("visit_point").where(new Where("status = ", STATUS_ENABLE).and("template_id=", id)).query().getResultObj();
	String pointIds = "-1";
	if (!isEmpty(points)) {
		boolean isEx = false;
		for (Map point:points) {
			Integer pointId = (Integer)point.get("id");
			pointIds = pointIds + "," + pointId;
			if (pointId.equals(startPointId)) {
				isEx = true;
				startPointMap.putAll(point);
			}
		}
		if (!isEx) {
			msg = new Message(30041, "基准节点不正确");
			Tools.encryptPrint(out, msg);
			return;
		}
	}
	List<Map> totalLinkList = QBuilder.db("basedb").select("new map(point_id as point_id, link_type as link_type, link_id as link_id)").from("visit_point_link").where(new Where("status = ", STATUS_ENABLE).and("point_id in(" + pointIds + ")")).query().getResultObj();
	Map<Integer, List<Map>> pointMap = new HashMap<Integer, List<Map>>();
	for (Map map:totalLinkList) {
		Integer pointId = (Integer)map.get("point_id");
		List<Map> list = pointMap.get(pointId) == null?new ArrayList<Map>():pointMap.get(pointId);
		list.add(map);
		pointMap.put(pointId, list);
	}
	List<String> currentUsedPatients = QBuilder.db("basedb").select("concat(v.patientUid, '')").from("Visit as v").where(new Where("v.category=", SURVEY_CATEGORY).and("v.status = ", STATUS_ENABLE).and("v.hospital=", hospital).and("v.workId=", id)).query().getResultObj();
	List<String> attentionUids = QBuilder.db("basedb").select("uid").from("OperateHistory").where(new Where("oid=", uid).and("status = ", STATUS_ENABLE).and("category=", SECTION_DOCTOR).and("operate=", ATTENTION)).query().getResultObj();
	// 不是自己的患者，移除出去,不允许发送随访;已经有这份随访方案的病人移除
	Iterator<String> iterator = patientUids.iterator();
	while(iterator.hasNext()) {
		String patientUid = iterator.next();
		if (!attentionUids.contains(patientUid) || currentUsedPatients.contains(patientUid))
			iterator.remove();
	}
	List<Integer> uidList = new ArrayList<Integer>();
	for (String patientUidString:patientUids) {
		uidList.add(Tools.getInt(patientUidString));
	}
	Map<Integer, User> userMap = usersByUids(uidList);
	List<Information> informations = new ArrayList<>();
	List<Visit> visits = new ArrayList<>();
	Date date = new Date();
	for (Integer patientUid:uidList) {
		User user = userMap.get(patientUid);
		if (isEmpty(user) || !user.getHospital().equals(hospital)) {
			// 患者不存在,略过
			continue;
		}
		UserProfile up = selfProfileByUid(patientUid);
		if (isEmpty(user.getName()) || up == null || isEmpty(up.getCardNumber())) {
			msg = new Message(30041, "患者未实名认证，暂不可进行随访");
			Tools.encryptPrint(out, msg);
			return;
		}
		Survey survey = new Survey();
		survey.setHospital(hospital);
		survey.setCategory(SURVEY_CATEGORY);
		survey.setBelong("schedule");
		survey.setTitle(Tools.getDesc(template.get("template_name")));
		survey.setEnable(STATUS_ENABLE);
		Integer surveyId = (Integer)DBTools.db("basedb").addItem(survey);

		String patientName = !isEmpty(user.getName())?user.getName():isEmpty(user.getNickName())?user.getUserName():user.getNickName();
		String dateStr = DateUtil.formatDateByFormat(date, "YY年MM月dd日");
		Integer startTimeDifference = (Integer)startPointMap.get("time_difference");
		String startDate = DateUtil.formatDateByFormat(start, "YY年MM月dd日");;
		String endDate = startDate;
		for (int i = 0; i < points.size(); i++) {
			Map point = points.get(i);
			Integer pointId = (Integer)point.get("id");
			Integer timeDifference = (Integer)point.get("time_difference");
			SurveyQuestion surveyQuestion = new SurveyQuestion();
			surveyQuestion.setHospital(hospital);
			surveyQuestion.setSurveyId(surveyId);
			Long time =  date.getTime();
			if (pointId >= startPointId) {
				Integer difference = timeDifference - startTimeDifference;
				time = DateUtil.afterNDay(start, difference).getTime();
			}
			String questTitle = Tools.getDesc(point.get("title"), "");
			List<Map> pointLinkList = pointMap.get(pointId);
			String questDetail = JSONUtil.toJson(pointLinkList);
			surveyQuestion.setcTime(time);
			surveyQuestion.setTitle(questTitle);
			surveyQuestion.setDetail(questDetail);
			surveyQuestion.setShowOrder(i + 1);
			surveyQuestion.setType(0);
			Integer scheduleId = (Integer)DBTools.db("basedb").addItem(surveyQuestion);
			Visit visit = new Visit();
			visit.setHospital(hospital);
			visit.setDoctorUid(uid);
			visit.setPatientUid(patientUid);
			visit.setSurveyId(scheduleId);
			visit.setCategory(SURVEY_QUESTION_CATEGORY);
			visit.setCancel(SURVEY_PUSH_PATIENT);
			visit.setcTime(time);
			// 发送时间
			visit.setSendTime(DateUtil.formatDateByFormat(new Date(time), DateUtil.DATETIME_FORMAT));
			visit.setIsconfirmed(NO_PUSH);
			// 略过的节点自动确认
			if (pointId < startPointId) {
				visit.setIsconfirmed(CONFIRMED);
				visit.setReconfirmedTime(DateUtil.formatDateByFormat(new Date(time), DateUtil.DATETIME_FORMAT));
			}
			visit.setName(patientName);
			visits.add(visit);
			if (i == (points.size()-1))
				endDate = DateUtil.formatDateByFormat(new Date(time), "YY年MM月dd日");
		}
		Visit visit = new Visit();
		visit.setHospital(hospital);
		visit.setDoctorUid(uid);
		visit.setPatientUid(patientUid);
		visit.setSurveyId(surveyId);
		visit.setCategory(SURVEY_CATEGORY);
		visit.setCancel(SURVEY_PUSH_PATIENT);
		visit.setSendTime(DateUtil.formatDateByFormat(date, DateUtil.DATETIME_FORMAT));
		visit.setIsconfirmed(CONFIRMED);
		visit.setReconfirmedTime(DateUtil.formatDateByFormat(date, DateUtil.DATETIME_FORMAT));
		visit.setName(patientName);
		visit.setScore(id);
		visits.add(visit);
		Information info = new Information();
		info.setUid(patientUid);
		info.setOid(surveyId + "");
		info.setTitle(survey.getTitle());
		info.setSumary("随访提醒");
		String content = String.format("%s医生于%s对您发起了《%s》随访，随访时间为%s至%s，请密切关注哦", new Object[]{doctor.getName(), dateStr, survey.getTitle(), startDate, endDate});
		info.setContent(content);
		info.setCategory(2);
		info.setHospital(hospital);
		informations.add(info);
	}
	if (!isEmpty(visits))
		DBTools.db("basedb").addItem(visits);
	if (!isEmpty(informations))
		DBTools.db("basedb").addItem(informations);
	// 此处应加入推送代码
	Tools.encryptPrint(out, msg);
%>